import React, { useState, useEffect } from 'react';
import { Button, Spin, message } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import ApiService, { Homepage } from '../services/api';
import './index.css';

const HomePage: React.FC = () => {
  const [homepage, setHomepage] = useState<Homepage | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchHomepage();
  }, []);

  const fetchHomepage = async () => {
    try {
      setLoading(true);
      const data = await ApiService.getPublishedHomepage();
      setHomepage(data);
    } catch (error) {
      console.error('获取首页内容失败:', error);
      message.error('获取首页内容失败');
    } finally {
      setLoading(false);
    }
  };

  const handleViewDetails = () => {
    window.location.href = '/products';
  };

  if (loading) {
    return (
      <div className="loading-container">
        <Spin size="large" />
        <p>加载中...</p>
      </div>
    );
  }

  if (!homepage) {
    return (
      <div className="error-container">
        <p>暂无首页内容</p>
      </div>
    );
  }

  return (
    <div className="homepage-container">
      <div className="homepage-content">
        <h1 className="homepage-title">{homepage.title}</h1>
        <div 
          className="homepage-html-content"
          dangerouslySetInnerHTML={{ __html: homepage.content }}
        />
        <div className="homepage-actions">
          <Button 
            type="primary" 
            size="large"
            icon={<SearchOutlined />}
            onClick={handleViewDetails}
            className="view-details-btn"
          >
            查询详情
          </Button>
        </div>
      </div>
    </div>
  );
};

export default HomePage;
